package com.indigon.utils  {
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.System;
	import flash.text.TextField;
	import flash.utils.getTimer;
	
	public class PerformanceMonitor extends Sprite
	{
		public function PerformanceMonitor()
		{
			_textBox = new TextField();
			_textBox.text = "...";
			_textBox.textColor = 0x555555;
			_textBox.selectable = false;
			_oldT = getTimer();
			addChild(_textBox);
			addEventListener(Event.ENTER_FRAME, update, false, 0, true);
			this.mouseChildren = this.mouseEnabled = false;
		}
		
		protected function update(event:Event):void
		{
			var newT : uint = getTimer();
			var f1c  : uint = newT - _oldT;
			_mfpsCount     += f1c;
			if (_avgCount < 1)
			{
				_textBox.text = String((30000 / _mfpsCount).toPrecision(4)) + " FPS";
				_avgCount = 30;
				_mfpsCount = 0;
				_textBox.appendText("\n" + String((System.totalMemory / (1048576)).toPrecision(6)) + " MB");
			}
			_avgCount--;
			_oldT = getTimer();
			
			parent.setChildIndex(this, parent.numChildren - 1);
		}
		
		public static function recordTime():void
		{
			_msCounter = getTimer();
		}
		
		public static function getTime():uint
		{
			return getTimer() - _msCounter;
		}
		
		private var _textBox    : TextField;   
		private var _oldT       : uint;     
		private var _mfpsCount  : uint = 0;  
		private var _avgCount   : uint = 30;
		private static var _msCounter : uint = 0;
	}
}
